<?php

if ( $_SESSION['logueado'] == 1 ){
include('index.php');
}else{
?>
	<div id='div_form_signup'>
		<form method='post' id='form_signup' action=''>
			<table id='table_signup'>
			<tr>
			<td><input class='formarea' type='textarea' name='Name'></td>
			</tr>
			<tr>
			<td><input class='formarea' type='textarea' name='Email'></td>
			</tr>
			<tr>
			<td><input class='formarea' type='password' name='password1'></td>
			</tr>
			<tr>
			<td><input class='formarea' type='password' name='password2'></td>
			</tr>
			<tr>
			<td><input class='boton' type='submit' value='Start'></td>
			</tr>
			</table>
		</form>
	</div>
<?php
}
if (isset($_POST['Name']) && isset($_POST['Email']) && isset($_POST['password1']) && isset($_POST['password2']) ){
$Name = mysql_real_escape_string(trim(strip_tags($_POST['Name'])));
$Email = $_POST['Email'];
$Password1 = $_POST['password1'];
$Password2 = $_POST['password2'];
	
	if (!empty($Password1) && $Password1 == $Password2){
		$Password1= md5($Password1);
		$Nick = mysql_query(" SELECT Name FROM USERS WHERE Name = '$Name' ");
		$rowNick = mysql_num_rows($Nick);
		$email = mysql_query(" SELECT email FROM USERS");
		
		
		while ($rowEmail = mysql_fetch_array($email)){
			
			if ( $rowEmail['email'] == $Email ){
				$mailvalido=0;
				break;
			}else{
				$mailvalido=1;
			}
		}
		
		if (preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',
		$Email)) 
		{
			if ($rowNick==1 || $mailvalido==0){
				if ($rowNick==1){
					echo "<div id='sign_error'>User already exits</div>";
				}
				else if($mailvalido==0){
				
					echo "<div id='sign_error'>This mail has been used by another user</div>";
				
				}
				
			}else{
			
				$insert = mysql_query ( "INSERT INTO USERS ( Name,Password,email ) VALUES ( '$Name','$Password1','$Email')");
				echo "<div id='sign_ok'>Registered!</div>";	
				
			
			}
		}else{
		
			echo "<div id='sign_error'>correct format: mail@example.com </div>";
		}
			
	}else{
		if ( $Password1 != $Password2 ){
		
			echo "<div id='sign_error'>The passwords doesn't match!</div>";
		
		} else {
			echo "<div id='sign_error'>You must fill the fields!</div>";
		}
	
	}
}else{

}

?>